// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database();
//requset包
const request = require('request')

function getNewTicket(token) {

  let url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + token + "&type=wx_card";
  //新建promise对象，发起http统一下单请求
  return new Promise((resolve, reject) => {
    try {
      request.post({
          url: url,
          method: "GET",
        },
        function(error, response, body) {
          if (!error && response.statusCode == 200) {
            let newToken = JSON.parse(body)
            return resolve(newToken)
          } else {
            return reject(err)
          }
        })
    } catch (e) {
      return reject(err)
    }
  })


}
// 云函数入口函数
exports.main = async(event, context) => {
  //---------------------------------------------------------
  //读取上次存储的ticket和ticket_timestamp
  let ticket = '';
  let queryTicket = await db.collection('publicParams').get();
  if (queryTicket.errMsg != 'collection.get:ok') {
    return 'err01:读取云函数集合[publicParams]失败'
  }
  //---------------------------------------------------------
  //判断上次读取ticke时间与当前时间相距多久
  let record = queryTicket.data[0];
  let lastTime = record.ticket_last_timestamp; //上次记录ticket的时间戳
  let thisTime = Date.parse(new Date()) //当前时间的时间戳

  //(1) 没有过期，直接使用
  //---------------------------------------------------------
  if ((thisTime - lastTime) < 7000000) {
    return record.ticket;
  }
  //---------------------------------------------------------
  //(2) 过期了，重新获取并并更新数据库

  //先获取access_token
  let publicTokenPromise = await cloud.callFunction({
    name: 'getPublicAccessToken'
  })
  if (publicTokenPromise.errMsg != 'callFunction:ok'){
    return 'err02:执行云函数[getPublicAccessToken]失败'
  }
  let token = publicTokenPromise.result;
  if (token == '') {
    return 'err03:云函数[getPublicAccessToken]返回结果为空'
  }
  let httpTicket = await getNewTicket(token); //发出http请求获取新的ticket

  if ('ticket' in httpTicket) //
  {
    //(1)成功获取新的token
    //1.1 记录新的token和当前时间
    let update = await db.collection('publicParams').doc('XG6bk3kPDdDCJ5vz')
      .update({
        data: {
          ticket: httpTicket.ticket,
          ticket_last_timestamp: thisTime
        }
      })
    if (update.errMsg == 'document.update:ok') {
      return httpTicket.ticket;
    } else {
      return 'err04:http请求新获取的ticket写入失败'; 
    }
  } 
  else {
    return 'err05:http请求获取ticket失败'; 
  }

}